package com.boang.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import com.boang.entity.po.SysMenu;
import com.boang.service.SysMenuService;
import jakarta.annotation.Resource;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@SpringBootConfiguration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，定义详细认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            getAuthRules().forEach(menu ->
                    // 根据路由划分模块，不同模块不同鉴权
                    SaRouter.match(menu.getPath(), r -> StpUtil.checkPermission(menu.getPerms())));
        })).addPathPatterns("/**");
    }

    // 动态获取鉴权规则
    public List<SysMenu> getAuthRules() {
        return sysMenuService.list();
    }

    // Sa-Token 整合 jwt (Simple 简单模式)
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }
}
